package com.tastyshop.controller;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.tastyshop.domain.Email;
import com.tastyshop.domain.Member;
import com.tastyshop.service.Base64;
import com.tastyshop.service.MailService;
import com.tastyshop.service.MemberService;

@Controller
@SessionAttributes("member")
public class MemberController {

	@Autowired
	private MemberService service;

	@ModelAttribute
	public Member member(){
		return new Member();
	}
	// 회원가입
	// 회원가입 1단계 회원체크화면
	@RequestMapping(value = "join_check.do", method = RequestMethod.GET)
	public String joinCheckForm() {
		return "join_check";
	}

	// 회원가입 2단계 약관동의화면
	@RequestMapping(value = "join_agree.do", method = RequestMethod.POST)
	public String member(@ModelAttribute("member") Member member, HttpServletRequest request,
			Model model) {
		return "join_agree";
	}

	// 회원가입 3단계 정보입력화면
	@RequestMapping(value = "join_member.do", method = RequestMethod.GET)
	public String join_member() {
		return "join_member";
	}
	
    // 회원가입 3단계 회원정보저장
	@RequestMapping(value = "join_member.do", method = RequestMethod.POST)
	public String addMember(@ModelAttribute("member") Member member,
			HttpServletRequest request,	HttpSession session, Model model) {
				
			String email = (String) request.getParameter("email");
			String user_name = (String) request.getParameter("user_name");
			String nick_name = (String) request.getParameter("nick_name");
			String user_pw = (String) request.getParameter("user_pw");
			String encodePassword = new String(Base64.encode(user_pw.getBytes())); // 패스워드 암호화
			System.out.println(encodePassword);
			String mobile = (String) request.getParameter("mobile");
			String year = (String) request.getParameter("year");
			String month = (String) request.getParameter("month");
			if (month.length() == 1) {
				month = "0" + month;
			}
			String day = (String) request.getParameter("day");
			if (day.length() == 1) {
				day = "0" + day;
			}
			String birth = year + month + day;
			int gender = Integer.parseInt(request.getParameter("gender"));

			member.setEmail(email);
			member.setUser_name(user_name);
			member.setNick_name(nick_name);
			member.setUser_pw(encodePassword);
			member.setMobile(mobile);
			member.setBirth(birth);
			member.setGender(gender);
			service.addMember(member);
			
			model.addAttribute("member", member);
			// 세션에 이메일, 이름, 닉네임 담기
			session.setAttribute("email", email);
			session.setAttribute("user_name", user_name);
			session.setAttribute("nick_name", nick_name);
			return "redirect:join_finish.do";		
		
	}
	
	// 회원가입 결과
	@RequestMapping(value = "join_finish.do", method = RequestMethod.GET)
	public String joinFinishForm(){
		return "join_finish";
	}

	// 회원가입유무 체크 및  이메일 인증번호 발송	
	@Autowired
	private MailService mailService;

	@RequestMapping(value = "confirm_send.do", method = RequestMethod.POST)
	public ResponseEntity<String> confirmSend(
			@RequestParam(value = "email", required = true) String email,
			HttpServletRequest request) throws Exception {
		System.out.println("이메일갖고오냐=" + email);
		JSONObject obj = new JSONObject();
		HttpHeaders responseHeaders = new HttpHeaders();
		
		String checkEmail = service.checkMember(email);
				
		if (checkEmail == null) {

			// 인증번호 생성
			Random rnd = new Random();

			StringBuffer rndNum = new StringBuffer();

			for (int i = 0; i < 8; i++) {
				if (rnd.nextBoolean()) {
					rndNum.append((char) ((int) (rnd.nextInt(26)) + 97));
				} else {
					rndNum.append((rnd.nextInt(10)));
				}
			}
			String confirmNum = rndNum.toString();

			// 메일보내기
			Email mail = new Email();
			String subject = "[Tasty Shop] 회원가입 인증번호 발송입니다.";
			String reciver = email;
			String content = "요청하신 회원가입 인증번호는 [" + confirmNum + "]" + " "
					+ "입니다.";

			System.out.println("인증번호는 나오냐=" + confirmNum);

			mail.setSubject(subject);
			mail.setReciver(reciver);
			mail.setContent(content);
			mailService.SendEmail(mail);

			String message = "입력 된 메일주소로 인증번호가 발송되었습니다.";
			// 사용자가 입력한 이메일 주소에서 naver.com 같이 메일 이름 짤라내기
			int maillength = email.length();
			int indexof = email.indexOf("@");
			String sub = email.substring(indexof, maillength);
			String mailname = sub.substring(1, sub.length());
			
			obj.put("message", message);
			obj.put("confirmNum", confirmNum);
			obj.put("mailname", mailname);
		}else{
			String message = "이미 가입하셨습니다. 로그인 해주세요 :)";
			obj.put("message", message);
		}
		responseHeaders.add("Content-Type", "text/html; charset=UTF-8");
		return new ResponseEntity<String>(obj.toString(), responseHeaders,
				HttpStatus.CREATED);

	}

	// 닉네임중복체크
	@RequestMapping(value = "nickName_check.do", method = RequestMethod.POST)
	public ResponseEntity<String> nickNameCheck(
			@RequestParam(value = "nick_name", required = true) String nick_name,
			@ModelAttribute("member") Member member) {
		String check = "true";
		String nickNameCheck = service.nickNameCheck(nick_name);
		if (nickNameCheck != null) {
			check = "false";
		}
		JSONObject obj = new JSONObject();
		obj.put("check", check);

		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=UTF-8");
		return new ResponseEntity<String>(obj.toString(), responseHeaders,
				HttpStatus.CREATED);
	}

}